package com.ns.dcjh.utils;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.FileProvider;

import com.alibaba.fastjson.JSONObject;
import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloadListener;
import com.liulishuo.filedownloader.FileDownloader;
import com.ns.dcjh.bean.MessageEvent;
import com.ns.dcjh.constant.Constant;
import com.ns.dcjh.vo.KuaiShouInfoVo;
import com.ns.dcjh.vo.XiaoHongShuVo;
import com.orhanobut.logger.Logger;
import com.xingin.xhssharesdk.XhsShareSdkTools;
import com.xingin.xhssharesdk.callback.XhsShareCallback;
import com.xingin.xhssharesdk.callback.XhsShareRegisterCallback;
import com.xingin.xhssharesdk.core.XhsShareSdk;
import com.xingin.xhssharesdk.model.config.XhsShareGlobalConfig;
import com.xingin.xhssharesdk.model.other.VersionCheckResult;
import com.xingin.xhssharesdk.model.sharedata.XhsImageInfo;
import com.xingin.xhssharesdk.model.sharedata.XhsImageResourceBean;
import com.xingin.xhssharesdk.model.sharedata.XhsNote;
import com.xingin.xhssharesdk.model.sharedata.XhsVideoInfo;
import com.xingin.xhssharesdk.model.sharedata.XhsVideoResourceBean;

import org.apache.commons.lang3.StringUtils;
import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

public class XiaoHongShuUtils {
    private Context mContext;
    private XhsNote xhsNote;

    public XiaoHongShuUtils(Context context) {
        this.mContext = context;
        XhsShareSdk.registerApp(context,
                Constant.XIAOHONGSHU_CLIENT_KEY,
                new XhsShareGlobalConfig().setEnableLog(true).setClearCacheWhenShareComplete(true).setFileProviderAuthority("com.ns.dcjh.fileprovider"),
                new XhsShareRegisterCallback() {
                    @Override
                    public void onSuccess() {
                        Log.e("xhs", "onSuccess: 注册成功！");
                    }

                    @Override
                    public void onError(int i, String s, @Nullable Exception e) {
                        JSONObject extras = new JSONObject();
                        extras.put("errorCode", i);
                        extras.put("errorMsg", "注册失败");

                        MessageEvent msgEvent = new MessageEvent(Constant.MSG_EVENT_SHARE_XIAOHONGSHU_RESP);
                        msgEvent.setExtras(extras);
                        EventBus.getDefault().post(msgEvent);
                        Log.e(
                                "xhs",
                                "onError: 注册失败！errorCode: $errorCode errorMessage: $errorMessage exception: $exception" + e
                        );
                    }
                });
        XhsShareSdk.setShareCallback(new XhsShareCallback() {
            @Override
            public void onSuccess(String s) {
                JSONObject extras = new JSONObject();
                extras.put("errorCode", 1998);
                extras.put("errorMsg", "");

                MessageEvent msgEvent = new MessageEvent(Constant.MSG_EVENT_SHARE_XIAOHONGSHU_RESP);
                msgEvent.setExtras(extras);
                EventBus.getDefault().post(msgEvent);
                Log.e("xhs", "onSuccess: 分享成功！");
            }

            @Override
            public void onError(@NonNull String s, int i, @NonNull String s1, @Nullable Throwable throwable) {

            }

            @Override
            public void onError2(@NonNull String s, int i, int i1, @NonNull String s1, @Nullable Throwable throwable) {
                String errorInfo = getErrorInfo(i);
                JSONObject extras = new JSONObject();
                extras.put("errorCode", i);
                extras.put("errorMsg", errorInfo);

                MessageEvent msgEvent = new MessageEvent(Constant.MSG_EVENT_SHARE_XIAOHONGSHU_RESP);
                msgEvent.setExtras(extras);
                EventBus.getDefault().post(msgEvent);
                Log.e(
                        "xhs",
                        "onError: 分享失败！errorCode: $errorCode errorMessage: $errorMessage exception: $exception" + throwable
                );
            }
        });
    }

    public void share(XiaoHongShuVo vo) {
        xhsNote = new XhsNote();
        xhsNote.setTitle(vo.getTitle());
        xhsNote.setContent(vo.getContent());
        if (vo.getImgPath() != null) {
            shareImage(vo.getImgPath());
        }
        if (vo.getVideoPath() != null || vo.getVideoNBPath() != null) {
            startDownloadVideo(vo);
        }
    }

    public void shareImage(List<String> base64List) {
        List<XhsImageResourceBean> xhsImageResourceBeanList = new ArrayList<>();
        ArrayList<Bitmap> bitmapList = new ArrayList<>();
        for (String base64 : base64List) {
            Bitmap bitmap = BitmapUtils.base64ToBitmap(base64.split(",")[1], mContext);
            bitmapList.add(bitmap);
        }
        BitmapUtils.bitmapSaveFileToStorage(bitmapList).subscribe(new Observer<File>() {
            @Override
            public void onSubscribe(Disposable d) {
            }

            @Override
            public void onNext(File file) {
                Uri contentUri = FileProvider.getUriForFile(mContext, "com.ns.dcjh.fileprovider", file);
                // 授权给小红书访问路径
                mContext.grantUriPermission("com.xingin.xhs", contentUri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
                xhsImageResourceBeanList.add(new XhsImageResourceBean(contentUri));
                xhsNote.setImageInfo(new XhsImageInfo(xhsImageResourceBeanList));
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {
                XhsShareSdk.shareNote(mContext, xhsNote);
            }
        });
    }

    public void shareVideo(Uri videoFile, String coverImage) {
        if (coverImage != null) {
            Bitmap bitmap = BitmapUtils.base64ToBitmap(coverImage.split(",")[1], mContext);
            BitmapUtils.bitmapSaveFileToStorage(bitmap).subscribe(new Observer<File>() {
                @Override
                public void onSubscribe(@NonNull Disposable d) {

                }

                @Override
                public void onNext(@NonNull File file) {
                    Uri contentUri = FileProvider.getUriForFile(mContext, "com.ns.dcjh.fileprovider", file);
                    // 授权给小红书访问路径
                    mContext.grantUriPermission("com.xingin.xhs", contentUri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    xhsNote.setVideoInfo(new XhsVideoInfo(new XhsVideoResourceBean(videoFile), new XhsImageResourceBean(contentUri)));
                }

                @Override
                public void onError(@NonNull Throwable e) {

                }

                @Override
                public void onComplete() {
                    XhsShareSdk.shareNote(mContext, xhsNote);
                }
            });

        } else {
            xhsNote.setVideoInfo(new XhsVideoInfo(new XhsVideoResourceBean(videoFile)));
            XhsShareSdk.shareNote(mContext, xhsNote);
        }
    }

    private void startDownloadVideo(XiaoHongShuVo vo) {
        String video = StringUtils.isEmpty(vo.getVideoPath()) ? vo.getVideoNBPath() : vo.getVideoPath();
        if (StringUtils.isEmpty(video)) {
            ToastUtils.info(mContext, "无效的视频地址");
            return;
        }

        File file = FileUtils.getFile("video", "mp4");

        LoadingUtils mLoading = LoadingUtils.create(mContext).show();
        FileDownloader
                .getImpl()
                .create(video)
                .setPath(file.getAbsolutePath())
                .setListener(new FileDownloadListener() {
                    @Override
                    protected void pending(BaseDownloadTask task, int soFarBytes, int totalBytes) {

                    }

                    @Override
                    protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) {

                    }

                    @Override
                    protected void completed(BaseDownloadTask task) {
                        mLoading.dismiss();
                        Uri contentUri = FileProvider.getUriForFile(mContext, "com.ns.dcjh.fileprovider", file);
                        // 授权给微信访问路径
                        mContext.grantUriPermission("com.xingin.xhs", contentUri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
                        shareVideo(contentUri, vo.getCoverPath());
                    }

                    @Override
                    protected void paused(BaseDownloadTask task, int soFarBytes, int totalBytes) {

                    }

                    @Override
                    protected void error(BaseDownloadTask task, Throwable e) {
                        mLoading.dismiss();
                        Logger.d("下载视频失败");
                        vo.setVideoNBPath(vo.getVideoNBPath());
                        if (!StringUtils.equals(vo.getVideoPath(), vo.getVideoNBPath())) {
                            startDownloadVideo(vo);
                        } else {
                            ToastUtils.info(mContext, "下载视频失败");
                        }
                    }

                    @Override
                    protected void warn(BaseDownloadTask task) {
                        mLoading.dismiss();
                    }
                })
                .start();

    }

    public static String getXiaoHongShuPackage() {
        return XhsShareSdkTools.getXhsPackageName();
    }

    public static boolean isInstalled(Context context) {
        return XhsShareSdkTools.isXhsInstalled(context);
    }

    public String getErrorInfo(int errorCode) {
        String errorMessage;
        switch (errorCode) {
            case -20100001:
                errorMessage = "小红书未安装";
                break;
            case -20100002:
                errorMessage = "小红书版本号太低";
                break;
            case -20100003:
                errorMessage = "资源缺失，图文和视频都没传";
                break;
            case -20100004:
                errorMessage = "图片或者视频文件不存在";
                break;
            case -20100005:
                errorMessage = "文件处理失败";
                break;
            case -20100006:
                errorMessage = "生成跨应用 uri 失败";
                break;
            case -20100007:
                errorMessage = "分享方法重复调用，上次分享流程还没有结束";
                break;
            case -20100008:
                errorMessage = "鉴权失败";
                break;
            case -20100009:
                errorMessage = "打开分享页面失败";
                break;
            case -20100010:
            case -20100011:
                errorMessage = "传递数据有误";
                break;
            case -20100012:
                errorMessage = "分享时还没有注册过";
                break;
            case -20100013:
                errorMessage = "分享上下文为空";
                break;
            case -20100014:
                errorMessage = "sessionId 与上下文不一致";
                break;
            case -20100015:
                errorMessage = "数据处理错误";
                break;
            case -20100016:
                errorMessage = "IO 错误";
                break;
            case -20100017:
                errorMessage = "数据处理线程被打断";
                break;
            case -20100018:
                errorMessage = "JSON 处理错误";
                break;
            case -20100019:
                errorMessage = "无法打开小红书";
                break;
            case -20302001:
            case -20302002:
            case -20302003:
            case -20302004:
            case -20302006:
            case -20302999:
                errorMessage = "数据解析失败";
                break;
            case -20302005:
            case -20400001:
                errorMessage = "小红书内部被新的分享打断并替代";
                break;
            case -20400002:
                errorMessage = "无法发布，不满足小红书的发布规范";
                break;
            case -20400003:
                errorMessage = "用户取消发布";
                break;
            case -20400004:
                errorMessage = "分享过程中提前切回第三方 app，导致获取不到分享结果";
                break;
            default:
                errorMessage = "未知错误";
                break;
        }
        Log.e("xhs", errorMessage);
        return errorMessage;
    }
}
